package com.easemob.helpdesk.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.activity.UserActivity;
import com.easemob.helpdesk.bean.BaseWebResult;
import com.easemob.helpdesk.bean.PageWithRes;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.listener.OnDoubleClickListener;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.easemob.helpdesk.widget.AddrSearchView;
import com.easemob.helpdesk.widget.SwipeRefreshView;
import com.google.gson.Gson;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
import com.hyphenate.kefusdk.HDConnectionListener;
//import com.hyphenate.kefusdk.entity.HDMessageUser;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by liyuzhao on 05/04/2017.
 */

public class OwnerFragment extends Fragment implements AddrSearchView.searchListener {
	private static final String TAG = OwnerFragment.class.getSimpleName();

	private InputMethodManager inputMethodManager;

	private  void initFindView(View view){
		mListView=view.findViewById(R.id.owner_list);

		rl_owner=view.findViewById(R.id.rl_owner);
		mSwipeRefreshView=view.findViewById(R.id.swipe_owner_layout);
		emptyView=view.findViewById(R.id.emptyView);
		errorItem=view.findViewById(R.id.rl_owner_error_item);
		query=view.findViewById(R.id.query);

		clearSearch=view.findViewById(R.id.search_clear);
		ll_right=view.findViewById(R.id.ll_right);
		query=view.findViewById(R.id.query);
		filterText=view.findViewById(R.id.ib_add_task);
		searchIcon=view.findViewById(R.id.ib_menu_more);
		emptyText=view.findViewById(R.id.empty_text);

	}
	public ListView mListView;
	public RelativeLayout rl_owner;
	public SwipeRefreshView mSwipeRefreshView;
	public View emptyView;
	public RelativeLayout errorItem;
	public EditText query;
	public ImageButton clearSearch;
	public LinearLayout ll_right;
	public TextView filterText;

	public ImageView searchIcon;

	public TextView emptyText;


	private List<User> mList;
	private StringAdapter mAdapter;

	private AddrSearchView addrSearchView;

	/**
	 * 加载提示Dialog
	 */
	public Dialog pd = null;

	private static int curPage = 1;
	private static int totalPage = 0;
	//搜索字符串
	private String search_str = "";

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_owner, null);
		initFindView(view);

		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mList = new ArrayList<>();
		mAdapter = new StringAdapter();
		inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

		mListView.setAdapter(mAdapter);

		emptyText.setText(getResources().getString(R.string.HU_LI_ZHAN).equals(MainActivity.productKey)?"暂无用户":"暂无业主");

		// 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
		// 设置下拉进度的背景颜色，默认就是白色的
		mSwipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white);
		// 设置下拉进度的主题颜色
		mSwipeRefreshView.setColorSchemeResources(R.color.colorAccent,
				android.R.color.holo_blue_bright, R.color.colorPrimaryDark,
				android.R.color.holo_orange_dark, android.R.color.holo_red_dark, android.R.color.holo_purple);

		mSwipeRefreshView.setItemCount(20);

		// 手动调用,通知系统去测量
		mSwipeRefreshView.measure(0, 0);
		mSwipeRefreshView.setRefreshing(true);

		initEvent();
		initData();

	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();


	}

	private void initEvent() {

		rl_owner.setOnTouchListener(new OnDoubleClickListener(new OnDoubleClickListener.DoubleClickCallback() {
			@Override
			public void onDoubleClick() {
				//处理双击事件
				mListView.smoothScrollToPosition(0);
			}
		}));



		String strSearch ="请输入姓名或房间号";
		query.setHint(strSearch);
		query.setOnEditorActionListener(new TextView.OnEditorActionListener(){
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				if(arg1 == EditorInfo.IME_ACTION_SEARCH)
				{
					search_str = arg0.getText().toString();
					if(addrSearchView != null){
						addrSearchView.clearViewData();
					}

					filterText.setTextColor(Color.parseColor("#ffffff"));
					searchIcon.setImageResource(R.drawable.hk_select_icon);

					initData();
				}
				return false;
			}

		});

		query.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
									  int count) {

				if (s.length() > 0) {
					clearSearch.setVisibility(View.VISIBLE);
				} else {
					clearSearch.setVisibility(View.INVISIBLE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
										  int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		clearSearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				query.getText().clear();
				hideSoftKeyboard();

				search_str = "";
				initData();
			}

		});

		if (!getResources().getString(R.string.LI_XIAO_SHUANG).equals(MainActivity.productKey)){
			if (MainActivity.userRole == 1 && TextUtils.isEmpty(MainActivity.village)) {
				ll_right.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (addrSearchView == null) {
							addrSearchView = new AddrSearchView(getActivity(), OwnerFragment.this, false);
							addrSearchView.showSearchView();
							hideSoftKeyboard();

						} else {
							if (addrSearchView.isShowing()) {
								addrSearchView.hideSearchView();
							} else {
								addrSearchView.showView();
								hideSoftKeyboard();
							}
						}
					}

				});
			} else {
				ll_right.setVisibility(View.GONE);
			}
		}else {
			ll_right.setVisibility(View.GONE);
		}



		// 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
		mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				initData();
			}
		});

		// 设置下拉加载更多
		mSwipeRefreshView.setOnLoadMoreListener(new SwipeRefreshView.OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				loadMoreData();
			}
		});
	}

	private void loadMoreData() {

		if(totalPage < curPage){//如果超过页数后
			return;
		}

		curPage = curPage + 1;

		mSwipeRefreshView.setLoading(true);

		ApiService apiService = HKHttpUtils.getApiService();
		retrofit2.Call<BaseResponse<PageWithRes>> call = apiService.getOwnerList(MainActivity.ticket,String.valueOf(MainActivity.userId), String.valueOf(curPage), "20", search_str);
		call.enqueue(new HKResponseResultCallBack<PageWithRes>() {
			@Override
			public void onSuccess(PageWithRes pageWithRes) {
				List<User> users = pageWithRes.getRes();
				if(users.size() != 0){
					mList.addAll(users);
				}else{
					Toast.makeText(getActivity(), "没有更多的"+(getResources().getString(R.string.HU_LI_ZHAN).equals(MainActivity.productKey)?"用户":"业主"), Toast.LENGTH_SHORT).show();
				}

//						Toast.makeText(getActivity(), "加载了" + 20 + "条数据", Toast.LENGTH_SHORT).show();
				// 加载完数据设置为不加载状态，将加载进度收起来
				mSwipeRefreshView.setLoading(false);
			}

			@Override
			public void onGetDataFailed(int cd, String msg) {
				Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onFailed(retrofit2.Call call, Throwable t) {
				Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
			}
		});

//		OkHttpClient okHttpClient = new OkHttpClient();
//		RequestBody body = new FormBody.Builder()
//				.add("page", String.valueOf(curPage))
//				.add("pagesize", String.valueOf(20))
//				.add("search", search_str)
//				.build();
//
//		Request request = new Request.Builder()
//				.url(BuildConfig.API_URL + "housekeeper/ownerlistsearch")
//				.header("user_id", String.valueOf(MainActivity.userId))
//						.post(body)
//						.build();
//
//		Call call = okHttpClient.newCall(request);
//
//		call.enqueue(new Callback() {
//			@Override
//			public void onFailure(Call call, IOException e) {
//				e.printStackTrace();
//				getActivity().runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
//					}
//				});
//
//			}
//
//			@Override
//			public void onResponse(Call call, Response response) throws IOException {
//				final BaseWebResult result = CommonUtils.parseJsonWithGson(response.body().string(), BaseWebResult.class);
//
//				getActivity().runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						List<User> users = result.getData().getRes();
//						if(users.size() != 0){
//							mList.addAll(users);
//						}else{
//							Toast.makeText(getActivity(), "没有更多的业主", Toast.LENGTH_SHORT).show();
//						}
//
////						Toast.makeText(getActivity(), "加载了" + 20 + "条数据", Toast.LENGTH_SHORT).show();
//						// 加载完数据设置为不加载状态，将加载进度收起来
//						mSwipeRefreshView.setLoading(false);
//					}
//				});
//
//			}
//		});

	}


	private void initData() {
		curPage = 1;
		ApiService apiService = HKHttpUtils.getApiService();
		retrofit2.Call<BaseResponse<PageWithRes>> call = apiService.getOwnerList(MainActivity.ticket,String.valueOf(MainActivity.userId), String.valueOf(curPage), "20", search_str);
		call.enqueue(new HKResponseResultCallBack<PageWithRes>() {
			@Override
			public void onSuccess(PageWithRes pageWithRes) {
				mList.clear();
				mList.addAll(pageWithRes.getRes());
				totalPage = pageWithRes.getTotal_page();

				if(mList.size() == 0){
					mListView.setVisibility(View.GONE);
					emptyView.setVisibility(View.VISIBLE);
				}else{
					mListView.setVisibility(View.VISIBLE);
					emptyView.setVisibility(View.GONE);
					mAdapter.notifyDataSetChanged();
				}

				// 加载完数据设置为不刷新状态，将下拉进度收起来
				if (mSwipeRefreshView.isRefreshing()) {
					mSwipeRefreshView.setRefreshing(false);
				}
			}

			@Override
			public void onGetDataFailed(int cd, String msg) {
				Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onFailed(retrofit2.Call call, Throwable t) {
				Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
			}
		});
//		OkHttpClient okHttpClient = new OkHttpClient();
//
////		showLoading();
////		System.out.println("initData: " + String.valueOf(MainActivity.userId));
//
//
//		RequestBody body = new FormBody.Builder()
//				.add("page", String.valueOf(curPage))
//				.add("pagesize", String.valueOf(20))
//				.add("search", search_str)
//		.build();
//
//		Request request = new Request.Builder()
//				.url(BuildConfig.API_URL + "housekeeper/ownerlistsearch")
//				.header("user_id", String.valueOf(MainActivity.userId))
//						.post(body)
//						.build();
//
//		Call call = okHttpClient.newCall(request);
//
//		call.enqueue(new Callback() {
//			@Override
//			public void onFailure(Call call, IOException e) {
//				e.printStackTrace();
////				hideLoading();
//				getActivity().runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
//					}
//				});
//
//			}
//
//			@Override
//			public void onResponse(Call call, Response response) throws IOException {
//
//				final BaseWebResult result = CommonUtils.parseJsonWithGson(response.body().string(), BaseWebResult.class);
//				getActivity().runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
////						hideLoading();
//
//						mList.clear();
//						mList.addAll(result.getData().getRes());
//						totalPage = result.getData().getTotal_page();
//
//						if(mList.size() == 0){
//							mListView.setVisibility(View.GONE);
//							emptyView.setVisibility(View.VISIBLE);
//						}else{
//							mListView.setVisibility(View.VISIBLE);
//							emptyView.setVisibility(View.GONE);
//							mAdapter.notifyDataSetChanged();
//						}
//
//						// 加载完数据设置为不刷新状态，将下拉进度收起来
//						if (mSwipeRefreshView.isRefreshing()) {
//							mSwipeRefreshView.setRefreshing(false);
//						}
//					}
//				});
//
//			}
//		});

	}

	void hideSoftKeyboard() {
		if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getActivity().getCurrentFocus() != null)
				inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	public void showLoading() {
		//显示登录提示对话框
		pd = DialogUtils.getLoadingDialog(this.getContext(), "加载中...");
		pd.show();
	}

	public void hideLoading() {
		if(pd != null && pd.isShowing()){
			pd.dismiss();
		}
	}

	@Override
	public void addrSearchRes(String search, String city, String curCityPinyin, String village, String building, String unit, String edit_str) {
		search_str = search;

		query.getText().clear();
		// 如果是清空的话
		if(search.equals("")){
			filterText.setTextColor(Color.parseColor("#ffffff"));
			searchIcon.setImageResource(R.drawable.hk_select_icon);
		}else{
			filterText.setTextColor(Color.parseColor("#FFF16D"));
			searchIcon.setImageResource(R.drawable.hk_select_icon_data);
		}


		initData();
	}

	/**
	 * 适配器
	 */
	private class StringAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public User getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getActivity(), R.layout.item_contact, null);
			}

			ImageView icon = (ImageView) convertView.findViewById(R.id.contact_icon);
			TextView name = (TextView) convertView.findViewById(R.id.contact_name);
			TextView addr = (TextView) convertView.findViewById(R.id.contact_addr);
			ImageView vipIcon = ((ImageView) convertView.findViewById(R.id.vip_icon));

			String wxname = mList.get(position).getWxName();
			String wxhead = mList.get(position).getWxHeader();
			String truename = mList.get(position).getName();

			if (mList.get(position).getIsVip() == 1){
				vipIcon.setVisibility(View.VISIBLE);
			}else {
				vipIcon.setVisibility(View.GONE);
			}

			try {
				if(!CommonUtils.isBlank(truename)){
					name.setText(truename);
				}else{
					if(!CommonUtils.isBlank(wxname)) {
						if(!CommonUtils.isBlank(wxhead) && wxhead.equals("undefined")){
							name.setText(mList.get(position).getPhone());
						}else{
							String decodeStr = URLDecoder.decode(mList.get(position).getWxName(), "utf-8");
							name.setText(CommonUtils.subStringCN(decodeStr, 30));
						}
					}
				}

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				if(!CommonUtils.isBlank(wxname)) {
					name.setText(wxname);
				}
			}

			addr.setText(mList.get(position).getHomeAddress());

			//加载图片
			Glide.with(getActivity()).load(mList.get(position).getWxHeader())
					.diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_agent_avatar).error(R.drawable.default_agent_avatar)
					.into(icon);

			convertView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {

					Intent intent = new Intent();

//					HDMessageUser hdUser = new HDMessageUser();
//					String visitorId = mList.get(position).getId()+"_"+mList.get(position).getWxOpenId();

					intent.setClass(getActivity(), UserActivity.class);
					intent.putExtra("id", mList.get(position).getId());
					intent.putExtra("phone", mList.get(position).getPhone());
					intent.putExtra("wxHeader", mList.get(position).getWxHeader());
					intent.putExtra("homeAddress",  mList.get(position).getHomeAddress());
					intent.putExtra("idcardNumber", mList.get(position).getIdcardNumber());
					intent.putExtra("isVip",mList.get(position).getIsVip());
					intent.putExtra("level",mList.get(position).getLevel());
					intent.putExtra("detailLevel",mList.get(position).getDetailLevel());

					String wxname = mList.get(position).getWxName();
					try {
						if(!CommonUtils.isBlank(wxname)) {
							String decodeStr = URLDecoder.decode(wxname, "utf-8");
							intent.putExtra("wxname", decodeStr);
						}else{
							intent.putExtra("wxname", "");
						}

					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						intent.putExtra("wxname", wxname);
					}

					String name = mList.get(position).getName();

					if(!CommonUtils.isBlank(name)){
						intent.putExtra("name", name);
					}else{
						intent.putExtra("name", "");
					}

					intent.putExtra("originType", "rest");
					intent.putExtra("techChannelName", "");
//					intent.putExtra("visitorid", visitorId);
					intent.putExtra("chatGroupId", 0L);
					startActivity(intent);


//					Toast.makeText(getActivity(), "点击了第一条", Toast.LENGTH_SHORT).show();
				}
			});

			return convertView;
		}
	}


}
